import click

from project_name.ext.auth import create_user
from project_name.ext.database import db
from project_name.models import accounts, image_features


def create_db():
    """Creates database"""
    db.create_all()
    inspector = db.inspect(db.engine)
    table_exists = inspector.has_table("accounts") and inspector.has_table("image_features")

    if not table_exists:
        db.create_all()  # 创建所有表
        print("Created database tables!")

    # 检查admin记录是否存在
    admin = accounts.query.filter_by(id=1).first()
    if not admin:
        password = '123456'
        new_admin = accounts(
            id=1,
            username='admin',
            password=password,
            id_type=0
        )
        db.session.add(new_admin)
        db.session.commit()
        print("Created admin user!")
    else:
        print("Admin user already exists")

    # 添加json数据到mysql的示例
    # user = image_features(patient_name='Alice', features={'theme': 'dark', 'notifications': True})
    # db.session.add(user)
    # db.session.commit()


def drop_db():
    """Cleans database"""
    db.drop_all()
    return accounts.query.all()


def init_app(app):
    # add multiple commands in a bulk
    for command in [create_db, drop_db]:
        app.cli.add_command(app.cli.command()(command))

    # add a single command
    @app.cli.command()
    @click.option("--username", "-u")
    @click.option("--password", "-p")
    def add_user(username, password):
        """Adds a new user to the database"""
        return create_user(username, password)
